﻿using System;
using System.Collections.Generic;
using System.Text;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.IO;
using System.Drawing;

namespace ImageToPdf
{
    public class PDFSharpImages : Base
    {

        public PDFSharpImages(PdfDocument documnet)
            : base(documnet)
        {
        }

        public void DrawImage(XGraphics gfx, string jpegSamplePath)
        {
            // BeginBox(gfx, number, "DrawImage (original)");


            XImage image = XImage.FromFile(jpegSamplePath);
            //gfx.PageSize=image.PixelWidth

            

const double dx = 250, dy = 140;

 

double width = image.PixelWidth * 72 / image.HorizontalResolution;

double height = image.PixelHeight * 72 / image.HorizontalResolution;


           // double x = (gfx.PageSize.Width - image.PixelWidth * 72 / image.HorizontalResolution) ;
           // double y = (gfx.PageSize.Height - image.PixelHeight * 72 / image.VerticalResolution) ;
//gfx.DrawImage(image, 0, 0, 592.28 , 841.89);
gfx.DrawImage(image, 0, 0, 600, 900);
             //EndBox(gfx);
        }

        //图片转为base64编码的字符串
        protected string ImgToBase64String(string Imagefilename)
        {
            try
            {
                Bitmap bmp = new Bitmap(Imagefilename);

                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        //threeebase64编码的字符串转为图片
        public static void Base64StringToImage(string imgfile,string strbase64)
        {
            try
            {
                if (strbase64.Contains(","))
                {
                    strbase64 = strbase64.Substring(strbase64.IndexOf(',')+1);
                }


                byte[] arr = Convert.FromBase64String(strbase64);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);

                bmp.Save(imgfile, System.Drawing.Imaging.ImageFormat.Jpeg);
                //bmp.Save(@"d:\"test.bmp", ImageFormat.Bmp);
                //bmp.Save(@"d:\"test.gif", ImageFormat.Gif);
                //bmp.Save(@"d:\"test.png", ImageFormat.Png);
                ms.Close();
                
            }
            catch (Exception ex)
            {
                
            }
        }
    }

}
